import { _decorator, Component } from 'cc';
import { TimeConst } from '../../Util/DateUtil';
import { CallBackHandler } from '../Model/PoolObj/CallBackHandler';
import { PoolManager } from '../Manager/PoolManager';
import { LogUtil } from '../../Util/LogUtil';
const { ccclass } = _decorator;
/* eslint-disable */
@ccclass('TimeControler')
export class TimeControler extends Component {
  /** 现在的时间 */
  nowTime: number = 0;
  /** 当天的零点 */
  todayZero: number = 0;
  /** 过零点的回调 */
  private callbacks: Map<string, CallBackHandler> = new Map();
  private timeCountFunc: Map<string, [number, CallBackHandler]> = new Map();

  protected start() {
    const time = new Date();
    this.nowTime = time.getTime();
    this.todayZero = time.setHours(0, 0, 0, 0);
    this.newDay();
  }

  private _time: number = 0;
  protected update(dt: number): void {
    this.nowTime += Math.floor(dt * TimeConst.Seconds);
    if (this.nowTime >= this.todayZero + TimeConst.Day) {
      const time = new Date();
      this.todayZero = time.getTime() - time.getHours() * TimeConst.Hours - time.getMinutes() * TimeConst.Minutes - time.getSeconds() * TimeConst.Seconds - time.getMilliseconds();
      this.newDay();
    }
    this._time += dt;
    if (this._time < 1) return;
    this._time = 0;
    this.checkTimeCount();
  }

  /** 绑定零点回调事件 */
  registerNewDay(type: string, callback: (...args: any[]) => void, target?: any, ...params: any[]) {
    if (this.callbacks.has(type)) {
      throw new Error('重复绑定时间回调函数');
    }
    const handler = PoolManager.Ins().popObj(CallBackHandler, type, callback, target, ...params);
    this.callbacks.set(type, handler);
  }

  unRegisterNewDay(type: string) {
    if (!this.callbacks.has(type)) {
      LogUtil.e('TimeControl:' + type, '没有绑定时间回调函数');
      return;
    }
    const handler = this.callbacks.get(type);
    PoolManager.Ins().pushObj(handler);
    this.callbacks.delete(type);
  }

  newDay() {
    this.callbacks.forEach((handler) => {
      handler.execute();
      PoolManager.Ins().pushObj(handler);
    });
  }

  /** 绑定全局计时器
   * @param type 计时器类型
   * @param time 倒计时（毫秒）
   * @param callback 回调函数
   * @param target 回调函数的this对象
   * @param params 回调函数的参数
   */
  registerTimeCountDown(type: string, time: number, callback: (...args: any[]) => void, target?: any, ...params: any[]) {}

  /** 绑定全局计时器
   * @param type 计时器类型
   * @param time 计时时间（时间点，时间戳 （毫秒））
   * @param callback 回调函数
   * @param target 回调函数的this对象
   * @param params 回调函数的参数
   */
  registerTimeCount(type: string, time: number, callback: (...args: any[]) => void, target?: any, ...params: any[]) {
    if (this.timeCountFunc.has(type)) {
      LogUtil.e('TimeControl:' + type, '重复绑定时间回调函数');
      return;
    }
    const handler = PoolManager.Ins().popObj(CallBackHandler, type, callback, target, ...params);
    this.timeCountFunc.set(type, [time, handler]);
  }

  unRegisterTimeCount(type: string) {
    if (!this.timeCountFunc.has(type)) {
      LogUtil.e('TimeControl:' + type, '没有绑定时间回调函数');
      return;
    }
    const handler = this.timeCountFunc.get(type)[1];
    PoolManager.Ins().pushObj(handler);
    this.timeCountFunc.delete(type);
  }

  checkTimeCount() {
    const keysToRemove: string[] = [];
    this.timeCountFunc.forEach((func, key) => {
      if (this.nowTime >= func[0]) {
        func[1].execute();
        keysToRemove.push(key);
      }
    });
    keysToRemove.forEach((key) => {
      this.timeCountFunc.delete(key);
    });
  }
}
